<template>
	<view class="poster">
		<!-- <view class="backGround" id="content-to-save">
			<view>
				<view class="title1">
					扫码领取
				</view>
				<view class="title1">
					价值300元红包
				</view>
			</view>

			<view class="title3">
				注册牙荷看牙有优惠
			</view>
			<view class="qcode">

			</view>

			<view class="mine-header">
				<view class="header-title">
					<image src="@/static/gray.jpg" mode="aspectFill" class="header-logo"></image>
					<view class="h2">小qi</view>
				</view>

				<view class="header-info">
					<image src="@/static/mine/yaheTitle@2x.png" class="img" mode="aspectFill"></image>
					<view class="infoTitle">
						牙YAHE荷
					</view>
				</view>

			</view>

		</view> -->
		<uqrcode v-show="false" ref="uqrcode" canvas-id="qrcode" :value="qrCodeImg" :options="{ margin: 10 }"></uqrcode>

		<canvas id="myCanvas" canvas-id="myCanvas" style="width: 80%; height: 900rpx; margintop: 100rpx"></canvas>
		<button class="button" @click="saveToAlbum">保存到相册</button>
	</view>
</template>

<script>
import UQRCode from '@/uni_modules/Sansnn-uQRCode/js_sdk/uqrcode/uqrcode.js';

export default {
	data() {
		return {
			canvasContext: null,
			canvasWidth: 0,
			canvasHeight: 0,
			info: {},
			qrCodeImg: '',
			dpr: 1,

		};
	},
	onReady() {
		this.initCanvas();
		this.$get('/yahe/hierarchy/inviteUrl').then((res) => {
			this.qrCodeImg = res.content?.inviteUrl;
		});
	},
	onShow() {
		this.info = uni.getStorageSync('user');
	},
	methods: {
		async initCanvas() {
			const query = uni.createSelectorQuery().in(this);
			query
				.select('#myCanvas')
				.fields({
					node: true,
					size: true
				})
				.exec(async (res) => {
					this.canvasWidth = res[0].width;
					this.canvasHeight = res[0].height;
					
					const ctx = uni.createCanvasContext('myCanvas', this);
					this.canvasContext = ctx;
					
					const systemInfo = uni.getSystemInfoSync();
					this.dpr = systemInfo.pixelRatio;

					ctx.mozImageSmoothingEnabled = false;
					ctx.webkitImageSmoothingEnabled = false;
					ctx.imageSmoothingEnabled = false;


					const path = await this.drawBackground();
					ctx.drawImage(path, 0, 0, this.canvasWidth, this.canvasHeight);

					const y = this.canvasHeight / 1.15;
					const drawAvatarPath = await this.drawAvatar(y);
					ctx.save();
					ctx.beginPath();
					ctx.arc(30 + 20, y + 20, 20, 0, Math.PI * 2, true); // 创建一个圆形路径
					ctx.closePath();
					ctx.clip();
					ctx.drawImage(drawAvatarPath, 30, y, 40, 40);
					ctx.restore();
					ctx.font = '10px Arial';
					ctx.fillStyle = 'white';
					ctx.fillText(this.info.nickName, 30 + 40 + 5, y + 20 + 5);

					this.drawQrCode();
				});
		},
		async drawBackground() {
			const ctx = this.canvasContext;

			return new Promise((resolve) => {
				uni.getImageInfo({
					src: 'https://fine-yahe.oss-cn-shanghai.aliyuncs.com/app/enterpriseCenter/poster.png',
					success: (avatarImageRes) => {
						resolve(avatarImageRes.path);
					},
					fail: (avatarImageErr) => {}
				});
			});
		},
		getPath(code) {
			const fs = uni.getFileSystemManager();
			const times = new Date().getTime();
			const codeimg = uni.env.USER_DATA_PATH + '/' + times + '.png';
			fs.writeFile({
				filePath: codeimg,
				data: code.slice(22),
				encoding: 'base64',
				success: () => {
					this.drawImage(codeimg);
				}
			});
		},
		drawImage(code) {
			const ctx = this.canvasContext;
			ctx.drawImage(code, this.canvasWidth / 3.33, this.canvasHeight / 2, this.canvasWidth / 2.5, this.canvasWidth / 2.5);
			ctx.draw(true);
		},

		drawQrCode() {
			const ctx = this.canvasContext;
			this.$refs.uqrcode.toTempFilePath({
				success: (res) => {
					this.getPath(res.tempFilePath);
				}
			});
		},

		async drawAvatar(y) {
			const ctx = this.canvasContext;
			ctx.drawImage('/static/mine/yaheTitle@2x.png', this.canvasWidth - 60, y, 30, 20);
			ctx.font = '10px Arial';
			ctx.fillStyle = 'white';
			ctx.fillText('牙YAHE荷', this.canvasWidth - 68, y + 20 + 15);

			return new Promise((resolve) => {
				uni.getImageInfo({
					src: this.info.avatar,
					success: (avatarImageRes) => {
						resolve(avatarImageRes.path);
					},
					fail: (avatarImageErr) => {
						console.error('获取头像图片信息失败', avatarImageErr);
					}
				});
			});
		},
		async saveToAlbum() {
			if (!this.canvasContext) return;
			const tempFilePath = await uni.canvasToTempFilePath({
				x: 0,
				y: 0,
				width: this.canvasWidth,
				height: this.canvasHeight,
				destWidth: this.canvasWidth * this.dpr,
				destHeight: this.canvasHeight * this.dpr,
				canvasId: 'myCanvas',
				success: (res) => {
					uni.authorize({
						scope: 'scope.writePhotosAlbum',
						success() {
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: () => {
									uni.showToast({
										title: '保存成功',
										icon: 'success'
									});
								},
								fail: (error) => {
									console.error('保存失败:', error);
									uni.showToast({
										title: '保存失败，请稍后再试',
										icon: 'none'
									});
								}
							});
						},
						fail() {}
					});
				}
			});
			console.log(tempFilePath, 3333);
			// uni.openSetting({
			// 	success(settingData) {
			// 		console.log('设置页面返回的数据:', settingData);
			// 		if (settingData.authSetting['scope.writePhotosAlbum']) {
			// 			console.log('用户已开启保存图片到相册的权限');
			// 		} else {
			// 			console.log('用户仍未开启保存图片到相册的权限');
			// 		}
			// 	},
			// 	fail(error) {
			// 		console.error('打开设置页面失败:', error);
			// 	}
			// });
		}
	}
};
</script>

<style scoped lang="less">
.poster {
	font-family: HarmonyOS Sans SC, HarmonyOS Sans SC;
	height: 95vh;
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 50rpx;
	padding-bottom: 30rpx;

	.backGround {
		margin-top: 160rpx;
		width: 80%;
		height: 852rpx;
		border-radius: 20rpx 20rpx 20rpx 20rpx;
		background-color: #00423b;
		padding: 60rpx 50rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
		box-sizing: border-box;

		.qcode {
			width: 288rpx;
			height: 288rpx;
			border-radius: 8rpx 8rpx 8rpx 8rpx;
			border: 2rpx solid;
			border-image: linear-gradient(270deg, rgba(253, 223, 198, 1), rgba(255, 245, 235, 1)) 2 2;
		}

		.title1 {
			font-family: eryaxindahei, eryaxindahei;
			font-weight: 400;
			font-size: 60rpx;
			line-height: 84rpx;
			text-align: center;
			font-style: normal;
			text-transform: none;
			color: #fbd6b6;
			// background: linear-gradient(16.766677991581346deg, #F5BB89 0%, #FBD6B6 26%, #FFF0E3 50%, #FCD9BB 76%, #F5BB89 100%);
		}

		.title3 {
			width: 274rpx;
			height: 54rpx;
			font-weight: 500;
			font-size: 24rpx;
			color: #fee2ca;
			line-height: 54rpx;
			text-align: center;
			background: rgba(254, 226, 202, 0.16);
			border-radius: 82rpx 82rpx 82rpx 82rpx;
			// margin-top: 50rpx;
		}

		.mine-header {
			display: flex;
			justify-content: space-between;
			width: 100%;

			.header-title {
				display: flex;
				justify-content: flex-start;
				align-items: center;

				.header-logo {
					width: 64rpx;
					height: 64rpx;
					border-radius: 50%;
					margin-right: 20rpx;
				}

				color: white;
			}

			.header-info {
				display: flex;
				flex-direction: column;
				align-items: center;

				.img {
					width: 52rpx;
					height: 42rpx;
				}

				.infoTitle {
					font-size: 20rpx;
					color: #fddfc6;
				}
			}
		}
	}

	.button {
		width: 80%;
		height: 80rpx;
		font-weight: 500;
		font-size: 28rpx;
		color: #ffffff;
		line-height: 80rpx;
		text-align: center;
		background: linear-gradient(90deg, #29d8c6 0%, #10beaf 100%);
		border-radius: 88rpx 88rpx 88rpx 88rpx;
	}
}
</style>
